/**
 * ejs文件说明
 * add-button.vue.ejs PC-list增加按钮
 * domain.java.ejs 实体类
 * edit-button.vue.ejs PC-list编辑按钮
 * form-data.js.ejs PC-表单初始化数据
 * form.vue.ejs PC-表单页面
 * index-edit.vue.ejs PC-组件编辑器属性页面
 * index.spec.js.ejs 前台-组件单元测试
 * index.vue.ejs 前台-组件
 * interface.java.ejs java-前台接口
 * list.vue.ejs PC-list页面
 * readme.md.ejs 前台-组件说明
 * route.js.ejs PC-路由定义
 * search-data.js.ejs PC-查询条件定义
 * service.java.ejs java-PC接口
 * sql.md.ejs java-sql文件
 * bus.js.ejs 前台-活动业务逻辑
 * logic.js.ejs 前台核销逻辑组件
 * 
 */
const $console = require("Console")
const fs = require('fs')
const ejs = require('ejs')
const shell = require("shelljs")
const path = require("path")
const userName = require('git-user-name')
const userEmail = require('git-user-email')
const p = function({
  fn,
  target,
  nodejs = true
}) {
  return (...args) => {
    // eslint-disable-next-line no-undef
    return new Promise((resolve, reject) => {
      args.push((err, ...data) => {
        if (nodejs === false) return resolve.apply(this, [err, ...
          data
        ])
        if (err === null || err === undefined) return resolve.apply(
          this, data)
        return reject(err)
      })
      if (target) fn.apply(target, args)
      else fn.apply(null, args)
    })
  }
}
const fs_readFile = p({
  fn: fs.readFile,
  target: fs
})
const fs_writeFile = p({
  fn: fs.writeFile,
  target: fs
})
const fs_stat_ = p({
  fn: fs.stat,
  target: fs
})
const fs_stat = async function(dir) {
  try {
    await fs_stat_(dir)
    return true
  } catch (e) {
    return false
  }
}
const fs_mkdir = p({
  fn: fs.mkdir,
  target: fs
})
const now = function() {
  const time = new Date()
  return `${time.getFullYear()}-${time.getMonth() + 1}-${time.getDate()} ${time.getHours()}:${time.getMinutes()}:${time.getSeconds()}`
}
const mkdirsSync = async dirpath => {
  if (await fs_stat(dirpath) === false) {
    let pathtmp;
    const pathes = dirpath.split(path.sep)
    for (let dirname of pathes) {
      if (pathtmp) {
        pathtmp = path.join(pathtmp, dirname);
      } else {
        pathtmp = dirname;
      }
      if (await fs_stat(pathtmp) === false) {
        await fs_mkdir(pathtmp)
      }
    }
  }
}
const baseDir = shell.pwd().stdout
const ejes = {}
module.exports = {
  async writeFile(txt, pathx, file, force) {
    if (force !== true && await fs_stat(`${pathx}${path.sep}${file}`)) {
      return
    }
    await mkdirsSync(pathx)
    await fs_writeFile(
      `${pathx}${path.sep}${file}`,
      txt, {
        encoding: 'utf-8'
      })
  },
  async render(name, data) {
    if (!ejes[name]) {
      const txt = await fs_readFile(path.join(baseDir, "auxi", "ejs",
        `${name}.ejs`))
      ejes[name] = txt.toString()
    }
    const txt = ejs.render(ejes[name], data)
    return txt
  },
  p,
  sep: path.sep,
  baseDir,
  fs_mkdir,
  mkdirsSync,
  fs_stat,
  fs_writeFile,
  fs_readFile,
  user: `${userName() || 'anonymous'}${userEmail() || ''}`,
  now
}